package com.hw.service.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hw.common.CommonConst;
import com.hw.entity.po.sys.SysMenu;
import com.hw.entity.bo.tree.SysMenuTreeBO;
import com.hw.mapper.sys.SysMenuMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单 Service实现类
 *
 * @author whw
 * @date 2021-06-21
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    @Override
    public List<SysMenuTreeBO> getTree(List<SysMenu> menus) {
        return buildTree(menus, CommonConst.EMPTY_UUID);
    }

    //region 构建树形数据

    /**
     * 构建树形数据
     *
     * @param menus
     * @param parentId
     * @return
     */
    private List<SysMenuTreeBO> buildTree(List<SysMenu> menus, String parentId) {
        List<SysMenuTreeBO> treeList = new ArrayList<>();
        List<SysMenu> roots = menus.stream().filter(item -> item.getMenuPid().equals(parentId)).collect(Collectors.toList());
        for (SysMenu item : roots) {
            SysMenuTreeBO root = buildMapTreeNode(item);
            buildTreeChildren(menus, root);
            treeList.add(root);
        }
        return treeList;
    }

    /**
     * 构建树节点
     *
     * @param data 数据
     * @return 树节点
     */
    private SysMenuTreeBO buildMapTreeNode(SysMenu data) {
        SysMenuTreeBO node = new SysMenuTreeBO();
        node.setId(data.getMenuId());
        node.setParentId(data.getMenuPid());
        node.setLabel(data.getMenuName());
        node.setUrl(data.getUrl());
        node.setComponentName(data.getComponentName());
        node.setSeq(data.getSeq());
        node.setValue(data.getMenuId());
        return node;
    }

    /**
     * 构建子节点
     *
     * @param datas      地图数据
     * @param parentNode 父节点
     */
    private void buildTreeChildren(List<SysMenu> datas, SysMenuTreeBO parentNode) {
        // 找出子节点
        List<SysMenu> children = datas.stream().filter(item -> item.getMenuPid().equals(parentNode.getId())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(children)) {
            //如果存在子节点，就实例化一个list用来存储子节点
            parentNode.setChildren(new ArrayList<>());
            for (SysMenu m : children) {
                SysMenuTreeBO rootNode = buildMapTreeNode(m);
                buildTreeChildren(datas, rootNode);
                parentNode.getChildren().add(rootNode);
            }
        }
    }
    //endregion

    @Override
    public List<SysMenu> list(List<String> permissionIds) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_deleted", 0)
                .in("c_permission_id", permissionIds)
                .orderByAsc("c_seq");
        return list(queryWrapper);
    }
}
